﻿using System.Data.SqlClient;
using NUnit.Framework;
using Patterns.DataProcessing.Aggregation;
using Patterns.Interfaces;
using System.Reflection;

namespace PatternTests
{
    [TestFixture]
    public class Deploiment
    {
        #region Helpers
        [Test]
        [Ignore]
        public void DeployAssemblies()
        {
            string connectionString = @"Data Source=PC-DE-OMAR\;Initial Catalog=test;Integrated Security=True";
            DeployAssembly(typeof(IAggregate).Assembly, connectionString);
            DeployAssembly(typeof(AggregateFactory).Assembly, connectionString);
        }

        [Test]
        [Ignore]
        public void RemoveAndDeployAssemblies()
        {
            RemoveAssemblies();
            DeployAssemblies();
        }

        [Test]
        [Ignore]
        public void RemoveAssemblies()
        {
            string connectionString = @"Data Source=PC-DE-OMAR\;Initial Catalog=test;Integrated Security=True";
            RemoveAssembly(typeof(AggregateFactory).Assembly, connectionString);
            RemoveAssembly(typeof(IAggregate).Assembly, connectionString);
        }
        #endregion

        #region Helpers
        private static void DeployAssembly(Assembly assembly, string connectionString)
        {
            string name = assembly.ManifestModule.ScopeName.Replace(".dll", "");
            string createQuery = string.Format("CREATE ASSEMBLY [{0}] FROM '{1}'", name, assembly.Location);
            ExecuteQuery(connectionString, createQuery);
        }

        private static void RemoveAssembly(Assembly assembly, string connectionString)
        {
            string name = assembly.ManifestModule.ScopeName.Replace(".dll", "");
            string dropQuery = string.Format("DROP ASSEMBLY [{0}] WITH NO DEPENDENTS", name);
            ExecuteQuery(connectionString, dropQuery);
        }

        private static void ExecuteQuery(string connectionString, string dropQuery)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                var dropCommand = new SqlCommand(dropQuery, connection);
                dropCommand.Connection.Open();
                dropCommand.ExecuteNonQuery();
            }
        }
        #endregion
    }
}
